package com.canbot.u05.versionupdate.utils;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.util.DisplayMetrics;

import com.canbot.u05.versionupdate.ApkFileInfo;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

/**
 * <pre>
 *     author: Blankj
 *     blog  : http://blankj.com
 *     time  : 2016/8/2
 *     desc  : App相关的工具类.
 * </pre>
 */
public final class AppUtils {

    private AppUtils() {
        throw new UnsupportedOperationException("u can't fuck me...");
    }

    /**
     * 获取栈顶的activityName.
     *
     * @param context 上下文
     * @return 栈顶activityName
     */
    public static String getTopActivityName(Context context) {
        String topActivityClassName = null;
        ActivityManager activityManager = (ActivityManager) (context
                .getSystemService(Context.ACTIVITY_SERVICE));
        List<RunningTaskInfo> runningTaskInfos = activityManager
                .getRunningTasks(1);
        if (runningTaskInfos != null) {
            ComponentName f = runningTaskInfos.get(0).topActivity;
            topActivityClassName = f.getClassName();
        }
        return topActivityClassName;
    }

    /**
     * 根据包名获取App的名字
     *
     * @param context
     * @return
     */
    public static String getAppName(Context context, ApkFileInfo apkFileInfo) {
        PackageInfo info = null;
        PackageManager pm = context.getPackageManager();
        String name = "";
        try {
            info = pm.getPackageInfo(apkFileInfo.getPackagename(), PackageManager.GET_ACTIVITIES);
            name = info.applicationInfo.loadLabel(pm).toString();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (name.equals("") || name.equals(apkFileInfo.getPackagename())) {
            name = getUninstallApkName(context, apkFileInfo.getApkFile().getAbsolutePath());
        }
        return name.equals("") ? apkFileInfo.getPackagename() : name;
    }

    public static String getUninstallApkName(Context context, String apkPath) {
        String PATH_PackageParser = "android.content.pm.PackageParser";
        String PATH_AssetManager = "android.content.res.AssetManager";
        try {
            Class pkgParserCls = Class.forName(PATH_PackageParser);
            Constructor pkgParserCt = pkgParserCls.getConstructor((Class[]) null);
            Object[] valueArgs = new Object[1];
            valueArgs[0] = apkPath;
            Object pkgParser = pkgParserCt.newInstance();
            DisplayMetrics metrics = new DisplayMetrics();
            metrics.setToDefaults();

            Class[] typeArgs = new Class[2];
            typeArgs[0] = File.class;
            typeArgs[1] = Integer.TYPE;

            //Method[] methods = pkgParserCls.getMethods();
            Method pkgParser_parsePackageMtd = pkgParserCls.getDeclaredMethod("parsePackage", typeArgs);
            valueArgs = new Object[2];
            valueArgs[0] = new File(apkPath);
            valueArgs[1] = 0;

            Object pkgParserPkg = pkgParser_parsePackageMtd.invoke(pkgParser, valueArgs);

            // 应用程序信息包, 这个公开的, 不过有些函数, 变量没公开
            // ApplicationInfo info = mPkgInfo.applicationInfo;
            Field appInfoFld = pkgParserPkg.getClass().getDeclaredField("applicationInfo");
            ApplicationInfo info = (ApplicationInfo) appInfoFld.get(pkgParserPkg);
            // uid 输出为"-1"，原因是未安装，系统未分配其Uid。
            Class assetMagCls = Class.forName(PATH_AssetManager);
            Constructor assetMagCt = assetMagCls.getConstructor((Class[]) null);

            Object assetMag = assetMagCt.newInstance((Object[]) null);
            typeArgs = new Class[1];
            typeArgs[0] = String.class;
            Method assetMag_addAssetPathMtd = assetMagCls.getDeclaredMethod("addAssetPath",
                    typeArgs);
            valueArgs = new Object[1];
            valueArgs[0] = apkPath;
            assetMag_addAssetPathMtd.invoke(assetMag, valueArgs);
            Resources res = context.getResources();

            typeArgs = new Class[3];
            typeArgs[0] = assetMag.getClass();
            typeArgs[1] = res.getDisplayMetrics().getClass();
            typeArgs[2] = res.getConfiguration().getClass();

            Constructor resCt = Resources.class.getConstructor(typeArgs);

            valueArgs = new Object[3];
            valueArgs[0] = assetMag;
            valueArgs[1] = res.getDisplayMetrics();
            valueArgs[2] = res.getConfiguration();


            res = (Resources) resCt.newInstance(valueArgs);

            if (info.labelRes != 0) {
                return res.getText(info.labelRes).toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
